package com.blb.trans.service.impl;

import com.blb.trans.entity.Goods;
import com.blb.trans.mapper.GoodsMapper;
import com.blb.trans.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private DataSourceTransactionManager transactionManager;

    @Override
    public void updateTwoGoods() {
        //启动事务
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        Goods goods = new Goods();
        goods.setId(1L);
        goods.setGoodsName("祖坟冒青烟");
        goods.setGoodsType("烟花");
        goods.setGoodsWeight(100);
        goodsMapper.updateGoods(goods);
        if(1 == 1) {
            throw new RuntimeException("Error!!");
        }
        Goods goods2 = new Goods();
        goods.setId(2L);
        goods.setGoodsName("祖坟冒青烟");
        goods.setGoodsType("烟花");
        goods.setGoodsWeight(100);
        goodsMapper.updateGoods(goods2);
        //提交事务后才能永久修改数据库
        transactionManager.commit(status);
        System.out.println("事务提交");
    }

}

